package com.xjl.example.atomic;

import com.xjl.annoations.ThreadSafe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

/**
 *
 * 原子性
 * Created by xiaojinlu1990@163.com on 2019/11/28.
 * Atomic 的int 方法 CAS方法确定线程安全
 */
@ThreadSafe
public class AtomicExample1
{
    private static Logger log = LoggerFactory.getLogger(AtomicExample1.class);
    //线程请求数
    private final static int clientTotal = 5000;
    //并发数
    private final static int threadTotal = 200;

    private static AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore  = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            });

        }

        executorService.shutdown();
        log.info(String.valueOf(count.get()));

    }

    private static void add() {
        count.incrementAndGet();
    }


}
